﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Linq.Expressions;

namespace System.Web.Mvc.Html
{
	public static class HtmlTableHelper
	{
		public static HtmlTableBuilder<T> TableFor<TModel, T>(this HtmlHelper<TModel> html, Func<TModel, IEnumerable<T>> selector)
		{
			var table = new HtmlTableBuilder<T>(selector(html.ViewData.Model));

			return table;
		}

		public static HtmlTableBuilder<T> WithColumns<T>(this HtmlTableBuilder<T> table, Action<HtmlTableColumnBuilder<T>> columnBuilder)
		{
			var cols = new HtmlTableColumnBuilder<T>();
			columnBuilder(cols);

			table.SetColumns(cols);

			return table;
		}

		public static HtmlTableBuilder<T> WithAttributes<T>(this HtmlTableBuilder<T> table, object htmlAttributes)
		{
			table.SetAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
			return table;
		}

		public static HtmlTableBuilder<T> WithRowAttributes<T>(this HtmlTableBuilder<T> table, object htmlAttributes)
		{
			return WithRowAttributes(table, htmlAttributes, r => true);
		}

		public static HtmlTableBuilder<T> WithRowAttributes<T>(this HtmlTableBuilder<T> table, object htmlAttributes, Func<HtmlTableRow<T>, bool> predicate)
		{
			var rowBuilder = new HtmlTableRowBuilder<T>();

			rowBuilder.Attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
			rowBuilder.Predicate = predicate;

			table.SetRowAttributes(rowBuilder);
			return table;
		}

		public static MvcHtmlString ToMvcHtmlString<T>(this HtmlTableBuilder<T> table)
		{
			return table.Build();
		}
	}
}
